//
//  YSPublishViewController.swift
//  新浪浪
//
//  Created by mac on 16/3/8.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SnapKit
import AFNetworking
import SVProgressHUD

let holderString = "下雨天和啪啪啪更配哦"


/*
***********************  一共要用到三个代理方法

*/
class YSPublishViewController: UIViewController ,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate  {
    
    /*
    ***********************  定义一个约束
    
    */
    var bottomConstraint: Constraint?
    
    /********************+++++++++++*********
                这里是viewDidLoad
    ***************+++++++++++*********************/
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.yellowColor()
        
        setupNav()
        setupTextView()
        setupTooBar()
        
        
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolBarFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "writeEmoticon:", name: kNotificationEmoticonTransform, object: nil)
        
        
        

    }
    
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem (title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem (title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "publish")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleLabel = UILabel (frame: CGRectMake(0, 0, 200, 44))
        
        titleLabel.numberOfLines = 0
        
        titleLabel.textAlignment = .Center
        
        let name = YSUserViewModel.shareInstance.model?.screen_name ?? ""
        let str = "发布微博\n\(name)"
        
        let attribute = NSMutableAttributedString (string: str)
        
        attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(15)], range: NSMakeRange(0, 4))
        
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(13),NSForegroundColorAttributeName:UIColor.orangeColor()], range: NSMakeRange(4, str.characters.count - 4))
        
        titleLabel.attributedText = attribute
        
        navigationItem.titleView = titleLabel
        
    }
    
    @objc private func dismiss(){
        dismissViewControllerAnimated((true)) { () -> Void in
            
        }
    }
    
    
    
    @objc private func publish(){
        
        var publishString: String = ""
        textView.attributedText.enumerateAttributesInRange(NSMakeRange(0, textView.attributedText.length), options: []) { (data:[String : AnyObject], range:NSRange, _) -> Void in
            if let attachment = data["NSAttachment"] as? YSTextAttachment {
                print(attachment.emoticon?.chs)
                publishString += attachment.emoticon!.chs!
            }else {
                let str = (self.textView.text as NSString) .substringWithRange(range)
                publishString += str
            }
        }
        
        let afn = AFHTTPSessionManager()
        let parameter = ["access_token":YSUserViewModel.shareInstance.access_token!,"status":publishString]
        
        afn.POST("https://api.weibo.com/2/statuses/update.json", parameters: parameter, progress: nil, success: { (_, JSON) -> Void in
            SVProgressHUD.dismiss()
            
            }) { (_, error) -> Void in
//                SVProgressHUD.showErrorWithStatus(error.discrption)
                SVProgressHUD.showErrorWithStatus(error.description)

        }
    }

    /*
    ***********************  设置TextView的属性
    
    */
    private func setupTextView(){
        
        view.addSubview(textView)
        textView.frame = view.frame
        textView.holderString = holderString
        textView.font = UIFont.systemFontOfSize(15)
        textView.delegate = self
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .OnDrag
        textView.addSubview(photoView)
        photoView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(textView.snp_center)
            make.width.equalTo(UIScreen.mainScreen().bounds.width - 2 * YSPhotoViewMargin)
            make.height.equalTo(UIScreen.mainScreen().bounds.width - 2 * YSPhotoViewMargin)
        }
    }
    /*
    ***********************  设置TextView的属性
    */
    
    /********************+++++++++++*********
    
    设置底部toobar
    ***************+++++++++++*********************/
    
    private func setupTooBar(){
        
        /*
        ***********************
        
        */
        toolBool.backgroundColor = UIColor.lightGrayColor()
        /*
        ***********************  设置toolBar
        
        */
        /********************+++++++++++*********
        
             定义一个数组里面是抽取的按钮的图片,方法
        
        ***************+++++++++++*********************/
        let itemSettings = [["imageName":"compose_toolbar_picture","action":"choosePicture"],
            ["imageName":"compose_mentionbutton_background"],
            ["imageName":"compose_trendbutton_background"],
            ["imageName":"compose_emoticonbutton_background","action":"inputEmoticon"],
            ["imageName":"compose_addbutton_background"]]
        
        // 定义一个空barbuttonItem的数组 存放toolBar里的按钮
        
            var items = [UIBarButtonItem]()
        
        /*
        ***********************  遍历数组里的按钮属性依次创建
        
        */
        for setting in itemSettings{
            
            
            let button = UIButton (type: UIButtonType.Custom)
            button.setImage(UIImage (named: setting["imageName"]!), forState: UIControlState.Normal)
            
            
            let imageName = setting["imageName"]!
            button.setImage(UIImage (named: "\(imageName)_highlighted"), forState: UIControlState.Highlighted)
            button.sizeToFit()
            
            /*
            ***********************  遍历数组里的按钮属性依次创建
            
            */
            
            
            
            if let action = setting["action"]{
                button.addTarget(self, action:Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            }
            
            
            let item = UIBarButtonItem (customView: button)
            
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        /*
        ***********************  遍历数组里的按钮属性依次创建按钮和弹簧
                            添加到空数组
        */
        
        /*
        ***********************  移除最后一个弹簧
        
        */
        items.removeLast()
        toolBool.items = items
        view.addSubview(toolBool)
        
        /*
        ***********************  设置toolBar的约束
        
        */
        toolBool.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            self.bottomConstraint = make.bottom.equalTo(view.snp_bottom).constraint
            make.height.equalTo(40)
        }
    }
    
    /*
    *********************** 实现点击图片添加图片的方法
    
    */
    @objc private func choosePicture(){
        /*
        ********************** 第一步 要判断一下 我们的手机能否访问相册
        
        */
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            
            let picker = UIImagePickerController()
            picker.sourceType = .PhotoLibrary
            
            //设置代理方法
            picker.delegate = self
            presentViewController(picker, animated: true, completion: { () -> Void in
                
            })
        }
            
        }
        //MARK: -- 显示表情
        @objc private func inputEmoticon(){
            print("显示表情")
            
            textView.resignFirstResponder()
            if textView.inputView == nil {
                textView.inputView = emotionView
            }else {
                textView.inputView = nil
            }
            textView.becomeFirstResponder()
        }
        
        //MARK: -- 键盘改变的通知
        func changeToolBarFrame(noti:NSNotification){
            if let info = noti.userInfo{
          //需要把NSRect转换成CGRect
                let endFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue
                
                if endFrame?.origin.y == (UIScreen.mainScreen().bounds.height){
                    print("退出的时候")
                    toolBool.snp_updateConstraints(closure: { (make) -> Void in

                        self.bottomConstraint = make.bottom.equalTo(view.snp_bottom).constraint
                    })
                }else {
                    print("弹出的时候")
                    //修改底部toobar的约束
                    toolBool.snp_updateConstraints(closure: { (make) -> Void in
                        self.bottomConstraint = make.bottom.equalTo(view.snp_bottom).offset(-endFrame!.size.height).constraint
                    })
                    
                    
                }
                
                //添加动画
                let duration = info[UIKeyboardAnimationDurationUserInfoKey]as! NSTimeInterval
                UIView.animateWithDuration(duration, animations: { () -> Void in
                    //更新动画约束
                    self.toolBool.layoutIfNeeded()
                })  
            }
    }
    
    
    @objc private func writeEmoticon(info:NSNotification){
        let emoticon = info.userInfo!["emoticon"]! as! YSEmotion
        if let png = emoticon.png {
            let beforeAttributtText = NSMutableAttributedString (attributedString: textView.attributedText)
            let attachment = YSTextAttachment()
            attachment.emoticon = emoticon
            let imagePath = "\(emoticon.path!)/\(png)"
            attachment.image = UIImage (named: imagePath)
            let attribut = NSAttributedString (attachment: attachment)
            let range = textView.selectedRange
            beforeAttributtText.insertAttributedString(attribut, atIndex: range.location)
            textView.attributedText = beforeAttributtText
            textView.selectedRange = NSMakeRange(range.location + 1, 0)
        }
    }
    
    
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardAnimationDurationUserInfoKey, object: nil)
        print("控制器88")
        NSNotificationCenter.defaultCenter().removeObserver(self, name: kNotificationEmoticonTransform, object: nil)
        
    }
    
    
    /********************+++++++++++*********
    
    懒加载
    ***************+++++++++++*********************/
    private lazy var textView:YSTextView = YSTextView()
    private lazy var toolBool: UIToolbar = UIToolbar()
    private lazy var emotionView: YSEmotionView = {
        let emo = YSEmotionView()
//        emo.backgroundColor = UIColor.purpleColor()
        emo.frame.size = CGSizeMake(UIScreen.mainScreen().bounds.width, 216)
        return emo
        
    }()
    
    
    
    private lazy var photoView: YSPhotoViiew = {
        let photo = YSPhotoViiew()
        
        //打破循环引用
        weak var weakself = self
        
        photo.closure = {[unowned self] ()->() in
            
            //去调用显示图片的方法
            
            weakself?.choosePicture()
        }
            return photo
    }()
}

//MARK:--UIImagePickerContrillerDelegate,UINavigationControllerDelegate

extension YSPublishViewController{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        /********************+++++++++++*********
        
        添加图片到图片选择器 不建议大家直接使用属性添加
        建议大家用方法
        ***************+++++++++++*********************/
        
        photoView.addImage(image)
        
        dismissViewControllerAnimated((true)) { () -> Void in
            
        }
    }
        func imagePickerControllerDidCancel(picker:UIImagePickerController){
            print("消失")
            dismissViewControllerAnimated((true
                )) { () -> Void in
                    
            }
        }
    }

//MARK: -- TextViewDelegate

extension YSPublishViewController{
    
    func textViewDidChange(textView: UITextView) {
        if textView.hasText(){
            self.textView.holderString = ""
        }else {
            //显示占位符
            self.textView.holderString = holderString
        }
        //重绘
        self.textView.setNeedsDisplay()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    
}



















